package com.chromatic.competition.view.notifications;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chromatic.competition.R;
import com.chromatic.competition.adapter.FriendsAdapter;
import com.chromatic.competition.databinding.FragmentNotificationsBinding;
import com.chromatic.competition.service.FriendsListFetchService;

import org.json.JSONException;
import org.json.JSONObject;
public class NotificationsFragment extends Fragment {
    private FragmentNotificationsBinding binding;
    private FriendsAdapter friendsAdapter;
    private FriendsListFetchService friendsListFetchService;
    private static final long REFRESH_INTERVAL = 500; // 刷新间隔0.5秒
    private Handler handler;
    private Runnable refreshRunnable;

    @SuppressLint("NotifyDataSetChanged")
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        int currentUserId;
        try {
            currentUserId = getCurrentUserId();
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
//        Log.d("目前在NotificationsFragment内", "用户账户的user_id是：" + currentUserId);

        // 初始化 FriendsViewModel
        friendsListFetchService = new ViewModelProvider(this).get(FriendsListFetchService.class);
        friendsListFetchService.setCurrentUserId(currentUserId);

        binding = FragmentNotificationsBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        RecyclerView recyclerView = binding.recyclerView;
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        friendsAdapter = new FriendsAdapter();
        recyclerView.setAdapter(friendsAdapter);

        // 观察 Friends 数据，更新适配器中的好友列表
        friendsListFetchService.getFriends().observe(getViewLifecycleOwner(), friends -> {
            friendsAdapter.setFriends(friends);
        });

        // 设置 AI 助手布局的点击事件，跳转到 SpeakActivity
        LinearLayout aiAssistantLayout = root.findViewById(R.id.ai_assistant);
        aiAssistantLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(requireActivity(), SpeakActivity.class);
                startActivity(intent);
            }
        });

        // 设置 AI 画板布局的点击事件，跳转到 PaintActivity
        LinearLayout aiPaintingLayout = root.findViewById(R.id.ai_painting);
        aiPaintingLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(requireActivity(), PaintActivity.class);
                startActivity(intent);
            }
        });

        ImageView addressBookView = root.findViewById(R.id.addressBook);
        addressBookView.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), FriendsAddActivity.class);
            startActivity(intent);
        });

        handler = new Handler();
        refreshRunnable = new Runnable() {
            @Override
            public void run() {
                refreshData(); // 调用刷新数据的方法
                handler.postDelayed(this, REFRESH_INTERVAL);
            }
        };

        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        startRefreshing(); // 在 onResume() 方法中启动刷新任务
    }

    @Override
    public void onPause() {
        super.onPause();
        stopRefreshing(); // 在 onPause() 方法中停止刷新任务
    }

    private void startRefreshing() {
        handler.postDelayed(refreshRunnable, REFRESH_INTERVAL);
    }

    private void stopRefreshing() {
        handler.removeCallbacks(refreshRunnable);
    }

    @SuppressLint("NotifyDataSetChanged")
    private void refreshData() {
        friendsListFetchService.loadFriendsListView();
        friendsAdapter.notifyDataSetChanged(); // 刷新 RecyclerView 的数据集和界面
    }

    private int getCurrentUserId() throws JSONException {
        SharedPreferences prefs = requireActivity().getSharedPreferences("login_info", Context.MODE_PRIVATE);
        String userJson = prefs.getString("user", "");
        JSONObject userObject = new JSONObject(userJson);
        return Integer.parseInt(userObject.getString("userId"));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}